﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.ComponentModel.Composition;
using Bzure.Common.Core;
using Bzure.Common.Events;
using Bzure.Common.HttpAspects;
using Bzure.Security.Principal;

namespace Bzure.Mvc
{
    [Export(typeof(IContractFactory<IHttpAspect>)), ExportMetadata("ProviderName", "_bzureRoutes")]
    public class RoutesHttpAspectBuilder : IContractFactory<IHttpAspect>
    {
        /// <summary>
        /// 契约实现的版本号
        /// </summary>
        public float ContractVersion { get { return 1.0F; } }
        public IHttpAspect Build()
        {
            return new RoutesHttpAspect();
        }
    }
    public class RoutesHttpAspect : IHttpAspect
    {
        public void InitAspect(IEventComponent<HttpEventOption, EventHandler> factory)
        {
            factory.AddEventHandler(HttpEventOption.AuthenticateRequest, new EventHandler(app_AuthenticateRequest));
            factory.AddEventHandler(HttpEventOption.EndRequest, new EventHandler(httpapp_EndRequest));
        }
        public void httpapp_EndRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Response.StatusCode == 401)
            {
                HttpContext context = HttpContext.Current;

                context.Response.StatusCode = 401;
                context.Response.AddHeader(
                    "WWW-Authenticate",
                    String.Format("Basic realm=\"{0}\"", "bzure security platform"));
            }
        }

        void app_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    var ticket = FormsAuthentication.Decrypt(cookie.Value);
                    if (!string.IsNullOrEmpty(ticket.UserData))
                    {
                        UserTicket ut = UserTicket.Build(ticket.UserData);
                        BzureUserModel userModel = new BzureUserModel(ut.User)
                        {
                            IsAuthenticated = true
                        };
                        BzurePrincipal BzurePrincipal = new BzurePrincipal(userModel)
                        {
                            TicketData = ut.TicketData
                        };
                        HttpContext.Current.User = BzurePrincipal;
                        System.Threading.Thread.CurrentPrincipal = BzurePrincipal;
                    }
                }
            }
        }
    }
}
